export default {
    //用于递归合并object
    forMerge(target, source) {
        for (let key in source) {
            if (source[key] && 'object' === typeof(source[key]) && !Array.isArray(source[key])) {
                if(!target[key] || 'object' !== typeof(target[key])) target[key] = {}
                this.forMerge(target[key], source[key])
            } else {
                target[key] = source[key]
            }
        }
        return target
    },
    //合并object
    merge(target) {
        let args = arguments, len = args.length
        if(!target || 'object' !== typeof(target)) return null
        for(let i=1; i<len; i++){
            if(args[i] && typeof(args[i]) === 'object') this.forMerge(target, args[i])
        }
        return target
    },
    //定义属性
    define(instance, data, options){
        const o = Object.assign({
            readonly: false,
            watch: false,
            custom: false
        }, options)
        options = null
        if(o.custom){
            Object.defineProperties(instance, data)
            return
        }
        let obj = instance
        if(o.key){
            let arr = o.key.split(/\./)
            arr.forEach(k => {
                if(!obj[k]) throw Error('对象上未定义属性' + o.key)
                obj = obj[k]
            })
        }
        for(let k in data){
            let old = data[k]
            if(o.readonly){
                Object.defineProperty(obj, k, {value: old})
            }else if(o.watch){
                Object.defineProperty(obj, k, {
                    set(val){
						if(old !== val || typeof(val) === 'object'){
                            if(instance.onSet) instance.onSet(k, val, old)
							instance.emit({
								type: k+'Change',
								oldValue: old,
								value: val
							})
							old = val
						}
					},
					get(){
						return old
					}
                })
            }else{
                Object.defineProperty(obj, k, {value: old, writable: true})
            }
        }
    }
}